package com.example.order_engine.application.service;

import com.example.order_engine.domain.event.OrderCreatedEvent;
import com.example.order_engine.domain.model.Order;
import com.example.order_engine.domain.service.OrderValidator;
import com.example.order_engine.domain.service.OrderAssembler;
import com.example.order_engine.domain.factory.OrderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 订单引擎服务 - 编排流程
 */
@Service
public class OrderEngineService {
    
    private final List<OrderValidator> validators;
    private final List<OrderAssembler> assemblers;
    private final List<OrderFactory> factories;
    private final ApplicationEventPublisher eventPublisher;
    
    @Autowired
    public OrderEngineService(List<OrderValidator> validators, 
                            List<OrderAssembler> assemblers, 
                            List<OrderFactory> factories,
                            ApplicationEventPublisher eventPublisher) {
        this.validators = validators;
        this.assemblers = assemblers;
        this.factories = factories;
        this.eventPublisher = eventPublisher;
    }
    
    /**
     * 创建订单
     * @param orderRequest 订单请求
     * @return 创建的订单
     */
    public Order createOrder(Map<String, Object> orderRequest) {
        String orderType = (String) orderRequest.get("orderType");
        
        // 1. 获取对应的工厂
        OrderFactory factory = factories.stream()
            .filter(f -> f.getSupportedOrderType().equals(orderType))
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException("不支持的订单类型: " + orderType));
        
        // 2. 创建订单
        Order order = factory.createOrder(orderRequest);
        
        // 3. 获取对应的校验器进行校验
        OrderValidator validator = validators.stream()
            .filter(v -> v.getSupportedOrderType().equals(orderType))
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException("找不到对应的校验器: " + orderType));
        
        if (!validator.validate(order)) {
            throw new IllegalArgumentException("订单校验失败");
        }
        
        // 4. 获取对应的组装器进行参数组装
        OrderAssembler assembler = assemblers.stream()
            .filter(a -> a.getSupportedOrderType().equals(orderType))
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException("找不到对应的组装器: " + orderType));
        
        Order assembledOrder = assembler.assemble(orderRequest);
        
        // 5. 发布领域事件
         eventPublisher.publishEvent(new OrderCreatedEvent(1,assembledOrder));
        
        return assembledOrder;
    }
}